import React, {PureComponent} from 'react';
import {connect} from 'dva';
import {
    Form, Input, Button, Card,Radio, Select,Cascader,Checkbox
} from 'antd';
const {Option} = Select;
const CheckboxGroup = Checkbox.Group;

import {message} from "antd/lib/index";
const FormItem = Form.Item;
const RadioGroup = Radio.Group;

@connect(state => ({
    submit: state.shipping,
}))
@Form.create()
export default class FreightTemplateEdit extends PureComponent {
    state={
        records:{},
        shippingRegion:[],
        checkOption:[],
        formValues:{},
        addCheck:'',
        CheckID:''
    }
    handleParentModalVisible = (e) => {
        this.state.checkOption=[];
        this.props.handleModalVisible();

    }

    isExit=(value)=>{
        return  value == this.state.addCheck;
    }

    insertAreas = () =>{
        // this.state.checkOption.map.has(this.state.addCheck);
        if(this.state.addCheck.length===0){
            message.info("请先选择地址")
        }
        else if(this.state.checkOption.length===0){
            this.setState({
                checkOption: this.state.checkOption.concat(this.state.addCheck),
            })
        }
       else if(this.state.checkOption.some(this.isExit)){
            message.info("该地区已存在")
        }else if(this.state.addCheck==='中国'){
            this.state.checkOption=[];
            this.setState({
                checkOption: this.state.checkOption.concat(this.state.addCheck),
            })
        }
        else{
            const {dispatch} = this.props;
            dispatch({
                type: 'shipping/queryCityIsExist',
                payload:{region_id:this.state.CheckID,
                    shipping_area_ids:this.state.checkOption,
                },
                callback: (response) => {
                    if (response.result === 0) {
                        this.setState({
                            checkOption: this.state.checkOption.concat(this.state.addCheck),
                        })
                    } else {
                        message.info("该地区已存在");
                    }
                }
            })

        }
    }


    addArea = (value,selectedOptions) => {
        const label = selectedOptions[selectedOptions.length-1].label;

        value = selectedOptions[selectedOptions.length-1].value;
        this.setState({
            addCheck:label,
            CheckID:value,
        });
    }


    componentDidMount() {

        const {dispatch} = this.props;
        const  {records,editType} = this.props;
        if(editType==='add'){
            this.setState({
                records:records
            });
        }else  if(records.shipping_area_ids) {
            this.setState({
                checkOption: records.shipping_area_ids.split(','),
                records:records
            });
        }

        dispatch({
            type: 'shipping/findParentNode',
            callback: (response) => {
                if (response.result === 0) {
                    this.setState({
                        shippingRegion: response.resultData.parentRegionList,
                    });
                } else {
                    message.success('失败');
                }
            }

        })
    }
    handleSubmit = (editType,shipping_templet_id,e) => {
        this.props.form.validateFieldsAndScroll((err, values) => {

            if (!err) {
                this.props.dispatch({
                    type: `shipping/${editType}`,
                    payload: {...values,shipping_templet_id: shipping_templet_id},
                    callback: (response) => {
                        if (response.result === 0) {
                            message.success('提交成功');
                            this.props.handleModalVisible(false);
                            this.props.success();
                            this.state.checkOption=[];
                        } else {
                            message.success('提交失败');
                        }
                    }
                });
            }
        });
    }


    render() {

        const { editType,submit,formValues} = this.props;
        const {submit:{data}} = this.props;
        const {records} = this.state;

        const {getFieldDecorator, getFieldValue} = this.props.form;
        const formInitValue = editType === 'add' ? formValues: records;
        const shipping_templet_attr_id = editType === 'add' ? '' : formInitValue.shipping_templet_attr_id ;
        const shipping_templet_id = formInitValue.shipping_templet_id ;


        const formItemLayout = {
            labelCol: {
                xs: {span: 12},
                sm: {span: 10},
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 12},
                md: {span: 10},
            },
        };
        const submitFormLayout = {
            wrapperCol: {
                xs: {span: 24, offset: 0},
                sm: {span: 10, offset: 7},
            },
        };





        return (
            <Card bordered={false}>
                <Form
                    onSubmit={this.handleSubmit}
                    hideRequiredMark
                >
                    <FormItem
                        {...formItemLayout}
                        label=""
                    >
                        {getFieldDecorator('shipping_templet_id', {
                            initialValue:  shipping_templet_id,
                        })(
                            <Input hidden/>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label=""
                    >
                        {getFieldDecorator('shipping_templet_attr_id', {
                            initialValue:  records.shipping_templet_attr_id,
                        })(
                            <Input hidden/>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="快递方式"
                    >
                        {getFieldDecorator('shipping_name', {
                            initialValue:  formInitValue.shipping_name || '',
                        })(
                         <Input/>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="区域名称"
                    >
                        {getFieldDecorator('shipping_area_name', {
                            initialValue:  formInitValue.shipping_area_name || '',
                            rules: [{
                                required: true, message: '请填写区域名称',
                            }]
                        })(
                            <Input/>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="费用计算方式"
                    >
                        {getFieldDecorator('shipping_fee_type', {
                            initialValue:  formInitValue.shipping_fee_type==='按重量计算'? 0:formInitValue.shipping_fee_type==='按重量计算'?1:'',
                            rules: [{
                                required: true, message: '请选择费用计算方式',
                            }]
                        })(
                            <RadioGroup>
                                <Radio value={0}>按重量计算</Radio>
                                <Radio value={1}>按商品件数计算</Radio>
                            </RadioGroup>

                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="首重1KG以内费用"
                    >
                        {getFieldDecorator('shipping_first_fee', {
                            initialValue:  formInitValue.shipping_first_fee,
                            rules: [{
                                required: true, message: '请设置首重1KG以内费用',
                            }]
                        })(
                            <Input />
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="续重每1KG或其零数的费用"
                    >
                        {getFieldDecorator('shipping_sec_fee', {
                            initialValue:  formInitValue.shipping_sec_fee,
                            rules: [{
                                required: true, message: '请设置续重每1KG或其零数的费用',
                            }]

                        })(
                            <Input />
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="免费额度"
                    >
                        {getFieldDecorator('shipping_free_fee', {
                            initialValue:  formInitValue.shipping_free_fee,
                            rules: [{
                                required: true, message: '请设置免费额度',
                            }]

                        })(
                            <Input/>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="货到付款"
                    >
                        {getFieldDecorator('shipping_goods_fee', {
                            initialValue:  formInitValue.shipping_goods_fee,
                            rules: [{
                                required: true, message: '请设置货到付款金额',
                            }]
                        })(
                            <Input/>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="到达目的地"
                    >
                        {getFieldDecorator('shipping_area_ids', {
                       //     initialValue:  formInitValue.shipping_area_ids,
                        })(
                            <Cascader options={this.state.shippingRegion} changeOnSelect onChange={this.addArea}  />
                            )}
                        <Button type="primary"  onClick={this.insertAreas} >
                            添加
                        </Button>
                        </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="区域"
                    >
                        {getFieldDecorator('shipping_area_id', {
                                initialValue:  this.state.checkOption,
                            rules: [{
                                required: true, message: '请添加配送地址',
                            }]
                        })(
                            <CheckboxGroup options={this.state.checkOption}  />
                        )}
                    </FormItem>


                    <FormItem {...submitFormLayout} style={{marginTop: 32}}>
                        <Button type="primary"  onClick={this.handleSubmit.bind(this,editType,shipping_templet_id)} >
                            确定
                        </Button>
                        <Button style={{marginLeft: 8}} onClick={this.handleParentModalVisible}>取消</Button>
                    </FormItem>
                </Form>

            </Card>
        );
    }
}
